package com.casework

class MeasureController {
    static scaffold = true

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def create = {
        def caseId = params.remove('caseId')
        def measureInstance = new Measure()
        measureInstance.properties = params
        return [measureInstance: measureInstance, caseId: caseId]
    }

    def show = {
        def measureInstance = Measure.get(params.id)

        if (!measureInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'measure.label', default: 'Measure'), params.id])
            redirect(action: "list")
        }
        else {
            def descriptions = LegalCaseNaceFullDescription.findAllByLegalCase(measureInstance.legalCase).collect { it.description } as Set
            def firms = LegalCaseFirm.findAllByLegalCase(measureInstance.legalCase).collect { it.firm } as Set

            [measureInstance: measureInstance, descriptions: descriptions.sort{a,b -> a.code <=> b.code}, firms: firms.sort{a,b -> a.name <=> b.name}]
        }
    }


    def save = {
        def measureInstance = new Measure(params)
        def legalCase = LegalCase.get(params.caseId)

        if (legalCase) {
                legalCase.addToMeasures(measureInstance)
                redirect action:'show', id: legalCase.id, controller: 'legalCase'
                return
            }
        if (measureInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'measure.label', default: 'Measure'), measureInstance.id])}"
            redirect(action: "show", id: measureInstance.id)
        }
        else {
            render(view: "create", model: [measureInstance: measureInstance, caseId: legalCase?.id])
        }
    }

    def classification = {
        def measureId = params.measureId
        def measure = Measure.get(measureId)

        def classificationId = params.classificationId
        if(!classificationId){
            render text:''
            return
        }

        def measureClassification = MeasureClassification.get(classificationId)
        def classificationProperties = ClassificationProperty.findAllByClassification(measureClassification)

        def properties = classificationProperties.collect{ it.property }
        render(view: 'properties', model:[measureInstance: measure, properties: properties])
    }
}
